import axios from 'axios'
import { getToken } from '../utils/utils.js'

class HttpRequest {
  constructor (baseUrl) {
    this.baseUrl = baseUrl
  }

  getInsideConfig () {
    let token = getToken()
    if (!token.startsWith('Bearer ')) {
      token = 'Bearer ' + token
    }
    const config = {
      baseURL: this.baseUrl,
      headers: {
        Authorization: token
      }
    }
    return config
  }

  interceptors (instance) {
    instance.interceptors.request.use(
      config => config,
      error => Promise.reject(error)
    )
    instance.interceptors.response.use(
      res => {
        const data = res.data
        return {
          data: data.data,
          message: data.message,
          success: data.success,
          total: data.total || null
        }
      },
      error => Promise.reject(error)
    )
  }

  request (options) {
    const instance = axios.create()

    const url = options.url
    if (
      url.toLowerCase().startsWith('http://') ||
      url.toLowerCase().startsWith('https://')
    ) {
    } else {
      options = Object.assign(this.getInsideConfig(), options)
      this.interceptors(instance)
    }

    return instance(options)
  }
}

export default HttpRequest
